import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

import javax.imageio.ImageIO;

public class NetworkInput extends Thread {

	NetworkHandler net;
	Images images;
	ClientGUI cgui;
	
	public NetworkInput(NetworkHandler networkHandler, Images images, ClientGUI cgui)
	{
		this.net = networkHandler; 
		this.images = images;
		this.cgui = cgui;
	}
	
	public void run()
	{
		while(true) {
			something();
		}
		
	}
	
	public void something() {
		//listen for image input, set image object
        try {
            while (true) {
            	/*
            	 * Read the type of request that we are going to receive,
            	 * we should receive either a webcam image och a map image.
            	 */
            	Byte request = net.getDin().readByte();
            	int nbrToRead = net.getDin().readInt();
            	Byte sample = (byte) nbrToRead;
            	byte[] byteArray = new byte[nbrToRead];
                int nbrRd = 0;
                int nbrLeftToRead = nbrToRead;
                while(nbrLeftToRead > 0){ 
                    int rd =net.getDin().read(byteArray, nbrRd, nbrLeftToRead);
                    if(rd < 0)
                        break;
                    nbrRd += rd; // accumulate bytes read
                    nbrLeftToRead -= rd;
                }
                //Converting the image
                ByteArrayInputStream byteArrayI = new ByteArrayInputStream(byteArray);
                BufferedImage image = ImageIO.read(byteArrayI);
                if(request == 0)
         	    	images.setMapImage(image);
         	    else if(request == 1)
         	    	images.setWebcamImage(image);
         	    cgui.update();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
	}
	
}